package com.fr.vod.videoshareucp_testprotocole;

import java.net.InetAddress;

import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import fr.vod.net.Receiver;
import fr.vod.net.ReceiverMulticast;
import fr.vod.net.Sender;
import fr.vod.net.SenderMulticast;
import fr.vod.util.LogHelper;

public class MainActivity extends Activity {

	// IHM elements

	private TextView msgEnvoi;
	private TextView msgRecu;
	private TextView info;
	private TextView role;
	private final int RECEIVE = 2;
	private final int SEND = 1;

	private Button boutonServer;
	private Button boutonClient;
	private Button boutonReinit;
	private int port = 3000;
	private String ipServer = "224.0.0.2";
	private String ipClient = "224.0.0.1";
	private String id = "01";
	private final int TIME_OUT = 2000;
	private String[] serverMessages = { "FILE_LENGTH_", "SERVER_READY_" };
	private String[] clientMessages = { "LENGTH_OK_", "CLIENT_READY_" };

	private Receiver receiver;
	private Sender sender;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		msgEnvoi = (TextView) findViewById(R.id.textVewEnvoi);
		msgRecu = (TextView) findViewById(R.id.textViewRecoit);
		info = (TextView) findViewById(R.id.textViewInfo);
		role = (TextView) findViewById(R.id.textViewRole);
		boutonClient = (Button) findViewById(R.id.buttonClient);
		boutonReinit = (Button) findViewById(R.id.buttonReinit);
		boutonServer = (Button) findViewById(R.id.buttonServer);

		initControlButton();

		/** configuration multicast **/
		WifiManager wifi = (WifiManager) getApplicationContext()
				.getSystemService(Context.WIFI_SERVICE);
		MulticastLock mLock = wifi.createMulticastLock("mylock");
		mLock.acquire();

	}

	private void initControlButton() {
		boutonClient.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				boutonClient.setVisibility(View.INVISIBLE);
				boutonServer.setVisibility(View.INVISIBLE);
				boutonReinit.setVisibility(View.VISIBLE);
				new Thread(new Runnable() {

					@Override
					public void run() {
						role.setText("Client");
						client();
					}

				}).start();
			}
		});
		boutonReinit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				MainActivity.this.recreate();
			}
		});
		boutonServer.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				boutonClient.setVisibility(View.INVISIBLE);
				boutonServer.setVisibility(View.INVISIBLE);
				boutonReinit.setVisibility(View.VISIBLE);
				new Thread(new Runnable() {

					@Override
					public void run() {
						role.setText("Server");
						server();
					}

				}).start();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	final Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == SEND) {
				msgEnvoi.setText(msgEnvoi.getText() + "\n" + (String) msg.obj);
			}
			if (msg.what == RECEIVE) {
				msgRecu.setText(msgRecu.getText() + "\n" + (String) msg.obj);
			}
		}
	};

	protected void sendMessage(int code, String str) {
		Message msg = handler.obtainMessage();
		msg.what = code;
		msg.obj = str;
		handler.sendMessage(msg);
	}

	protected void client() {
		String msg = "";
		int cpt = 0;
		try {
			sender = new SenderMulticast(InetAddress.getByName(ipServer), port);
			receiver = new ReceiverMulticast(InetAddress.getByName(ipClient),
					port);

			/** syncronisation file tranfert **/
			while (cpt < serverMessages.length) {
				do {
					msg = receiver.receive();
					sendMessage(RECEIVE, msg);
				} while (!msg.startsWith(serverMessages[cpt]));
				sender.send(clientMessages[cpt]);
				sendMessage(SEND, clientMessages[cpt]);
				cpt++;
			}

			LogHelper.information("Protocole", "FIN");
			/** flux data transfert **/

		} catch (Exception e) {
			e.printStackTrace();
			LogHelper.information("E", "erreur de MERDER");
		}
	}

	protected void server() {
		String msg = "";
		int cpt = 0;
		try {
			sender = new SenderMulticast(InetAddress.getByName(ipClient), port);
			receiver = new ReceiverMulticast(InetAddress.getByName(ipServer),
					port);

			/** syncronisation file tranfert **/
			while (cpt < serverMessages.length) {
				do {
					sender.send(serverMessages[cpt]);
					sendMessage(SEND, serverMessages[cpt]);
					msg = receiver.receiveTimeOut(TIME_OUT);
				} while (!msg.startsWith(clientMessages[cpt]));
				LogHelper.information("Protocole", "message client " + msg);
				sendMessage(RECEIVE, msg);
				cpt++;
			}

			LogHelper.information("Protocole", "FIN");
			/** flux data transfert **/

		} catch (Exception e) {
			e.printStackTrace();
			LogHelper.information("E", "erreur de MERDER");
		}
	}
}
